import React, { Component, createRef } from 'react'

import styles from './index.module.scss'

import PropTypes from 'prop-types'

export default class Sticky extends Component {
  contentRef = createRef()
  placeholderRef = createRef()
  handleScroll = () => {
    const contentDOM = this.contentRef.current
    const placeholderDOM = this.placeholderRef.current
    // console.log('滚动事件触发');
    // getBoundingClientRect() 原生JS DOM方法 获取盒子到可视区域的各项边距，返回一个对象
    const { top } = placeholderDOM.getBoundingClientRect()
    if(top <= 0) {
      // 固定
      // contentDOM.style.position = 'fixed'
      // contentDOM.style.top = '0px'
      contentDOM.classList.add(styles.fixed)
      placeholderDOM.style.height = `${this.props.height}px`
    } else {
      // 取消固定
      contentDOM.classList.remove(styles.fixed)
      placeholderDOM.style.height = '0px'
    }
  }
  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll)
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll)
  }
  render() {
    return (
      <>
        {/* 占位符，当内容div position: fixed 后生效，避免塌陷 */}
        <div ref={this.placeholderRef}></div>
        {/* 内容 */}
        <div ref={this.contentRef}>
            {this.props.children}
        </div>
      </>
    )
  }
}

Sticky.propTypes = {
  height: PropTypes.number.isRequired,
  children: PropTypes.node.isRequired
}

